package com.sensor.meter.fragment

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.FragmentManager
import com.sensor.meter.R
import org.jetbrains.annotations.NotNull

/**
 * @author       CT
 * @date         2024/3/4
 * @description   dialog Fragment
 *
 */
class DialogFra(@LayoutRes val layoutId: Int) : AppCompatDialogFragment() {

  val DIALOG_TAG="base_dialog"

  fun newInstance(@LayoutRes layoutId:Int): DialogFra{
    val fragment = DialogFra(layoutId)
    return fragment
  }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val  v = inflater.inflate(if (layoutId<=0) R.layout.dialog_light_meter_desc else layoutId ,container,false)
    dialog!!.window!!.requestFeature(Window.FEATURE_NO_TITLE)
    return v;
  }

  override fun onStart() {
    super.onStart()
    initDialog()
  }

  private fun initDialog(){
    val mDialog=dialog
    if(mDialog!=null){
      val window=mDialog.window
      if(window!=null){
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        //window.setBackgroundDrawableResource(R.color.color_mask)
        window.setWindowAnimations(R.style.dialog_window_anim_style)
        //
        val displayMetrics=requireContext().resources.displayMetrics
        window.attributes.width= (displayMetrics.widthPixels / 1.5).toInt()
        //window.attributes.height= displayMetrics.heightPixels / 2
        window.attributes.gravity=Gravity.CENTER
      }
      mDialog.setCancelable(true)
      //mDialog.setOnCancelListener {
      //  dismiss();
      //}
    }
  }

  open fun showDialogFragment(@NotNull fm: FragmentManager){
    val ft=fm.beginTransaction()
    val prevF=fm.findFragmentByTag(DIALOG_TAG)
    if(prevF!=null){
      ft.remove(prevF)
    }
    ft.add(this,DIALOG_TAG)
    ft.commitAllowingStateLoss()
  }

  fun dismiss(@NotNull fm:FragmentManager){
    val prev=fm.findFragmentByTag(DIALOG_TAG)
    if(prev!=null){
      val ft=fm.beginTransaction()
      ft.remove(prev)
      ft.addToBackStack(null)
      ft.commit()
    }
    super.dismiss()
  }
}